<template>
  <!-- 营销项目计划管理-提报明细页面 -->
  <div>
    <FormPanel ref="FormPanel" :list="initForm" :cols="2" :formType="options.formType" :labelWidth="150" :isSubmitBtn="false" @formChange="changeHandle" class="mtop" />
    <!-- 审核列表 -->
    <FilterTable
      ref="table"
      height="400"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="false"
      :onColumnsChange="(columns) => (this.columns = columns)"
      columnsRef="projectOperating_plan_approvalDetails_indexShow_01"
    >
    </FilterTable>
    <!-- 选择车型 -->
    <BaseDialog title="选择车型" :visible.sync="visibleDialog" width="700px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <infoModal selectType="multiple" @close="selectModelBack" />
    </BaseDialog>
    <!-- 选择方案 -->
    <BaseDialog title="选择项目" :visible.sync="visibleDialogPro" width="700px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <programModal selectType="single" @close="selectModelBackPro" />
    </BaseDialog>
    <div class="dialogBottmView">
      <el-button @click="closeDialog">关 闭</el-button>
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { formatdateByDay, formatdateByTime } from '@/utils/index';
import { getDetails, addData, editData, addSubmitData, editSubmitData, nullifyPlanById } from '@/api/cms-api/projectOperating/plan';
import infoModal from '@/pages/cms-common/model';
import programModal from '../../program/push/select';
import { getBigMarketType, getSmallMarketType } from '@/api/cms-api/projectOperating/plan/index';
import { getList } from '@/api/cms-api/projectOperating/program/oemInquire/index';
import * as types from '@/api/cms-api/projectOperating/plan/types';
import { getDealerAttachModel, getModelAllListOEM } from '@/api/common/cars/brandcarsModels/index'; // 获取全部车型

export default {
  mixins: [dictionary],
  components: {
    infoModal,
    programModal,
  },
  props: {
    options: {
      type: Object,
      required: true,
      default: () => {},
    },
  },
  data() {
    return {
      initForm: this.creatFilterList(),
      columns: this.creatHeader(),
      fetchApi: getList, //审核列表
      fetchParams: { planId: this.options.id }, //参数
      formData: {},
      visibleDialog: false,
      visibleDialogPro: false,
      modelIdList: [],
      modelName: '',
      saveLoading: false,
      bigType: [], //存储项目大类集合
      infoBasic: this.options.formType,
      projectProgramId: 0, //项目id
    };
  },
  mounted() {
    //如果类型为添加，则不查询
    if (this.options.formType != 'add') {
      this.init();
    }
    //初始化项目大类
    this.initBigMarketType();
    //表单赋值车型
    this.getModelAllListOEM();
  },
  methods: {
    async init() {
      let res = await getDetails(this.options.id, {});
      if (res.resultCode === 200) {
        this.formData = res.data;
        //给表单赋值
        this.initForm.forEach((x) => {
          if (x.fieldName == 'uploadFileList') {
            //如果为附件
            let urlsList = this.formData.urls;
            if (urlsList != null && urlsList.length > 0) {
              let fileList = [];
              for (let i in urlsList) {
                let fileName = { name: urlsList[i].fileName };
                let fileId = { url: urlsList[i].fileId };
                let f = Object.assign(fileName, fileId);
                fileList.push(f);
              }
              x.initialValue = fileList;
            }
          } else if (x.fieldName == 'model') {
            //如果为车型
            x.initialValue = this.formData.modelList;
          } else if (x.fieldName == 'projectMainClass') {
            //如果为大类，则初始化小类
            x.initialValue = this.formData[x.fieldName];
            if (this.formData.projectMainClass != null && this.formData.projectMainClass != '') {
              this.initMarketTypeSmall(this.formData.projectMainClass);
            }
          } else if (x.fieldName == 'planLaunchReleaseTimeList') {
            //如果为计划开展/投放时间
            if (this.formData['planLaunchReleaseTime'] != null && this.formData['planLaunchReleaseTime'] != '') {
              let releaseTime = this.formData['planLaunchReleaseTime'].split(',');
              x.initialValue = releaseTime;
            }
          } else if (x.fieldName == 'planApproveAmount') {
            if (x.initialValue == null) {
              x.initialValue = 0;
            }
          } else if (x.fieldName == 'planBoothAmount') {
            if (x.initialValue == null) {
              x.initialValue = '';
            }
          } else if (x.fieldName == 'planBuildAmount') {
            if (x.initialValue == null) {
              x.initialValue = '';
            }
          } else {
            x.initialValue = this.formData[x.fieldName];
          }
        });
      }
    },
    //车型弹窗打开
    openModelDialog() {
      this.visibleDialog = true;
    },
    //获取所有车型数据
    async getModelAllListOEM() {
      this.loginUser = await getLoginUser({});
      let attachModelRes = await getDealerAttachModel(this.loginUser.data.companyCode, []); //经销商编号
      if (attachModelRes.resultCode === 200) {
        if (attachModelRes.data) {
          let inModelList = [];
          let mapModel = {};
          attachModelRes.data.forEach((x) => {
            inModelList.push(x.modelId);
          });
          if (inModelList) {
            if (Array.isArray(inModelList)) {
              mapModel = { inModel: inModelList.join(',') };
              let res = await getModelAllListOEM(mapModel);
              if (res.resultCode === 200) {
                this.initForm.find((item) => item.fieldName === 'modelList').itemList = [];
                res.data.forEach((x) => {
                  this.initForm.find((item) => item.fieldName === 'modelList').itemList.push({ text: x.modelName, value: x.modelId });
                });
              }
            }
          }
        }
      }
    },
    //车型弹窗关闭
    selectModelBack(data) {
      if (data && data.data && typeof data.data != null) {
        //清空数据
        this.modelIdList = [];
        this.modelName = '';
        //循环返回数据
        data.data.forEach((x) => {
          //循环判断是否已选择过该车型
          let isHave = false;
          for (let i = 0; i < this.modelIdList; i++) {
            if (this.modelIdList[i] == x.modelId) {
              isHave = true;
            }
          }
          //插入车型id
          if (!isHave) {
            this.modelIdList.push(x.modelId);
          }

          //使用逗号分隔拼接车型名称
          if (this.modelName == '') {
            this.modelName = x.modelName;
          } else {
            this.modelName += ',' + x.modelName;
          }
        });

        //显示车型名称
        this.initForm[2].initialValue = this.modelName;
      }

      this.visibleDialog = false; //关闭弹窗
    },
    //项目弹窗打开
    openModelDialogPro() {
      this.visibleDialogPro = true;
    },
    //项目弹窗关闭
    selectModelBackPro(data) {
      if (data && data.data && typeof data.data != null) {
        this.projectProgramId = data.data[0].projectProgramId;
        this.initForm[14].initialValue = data.data[0].programCode;
        this.initForm[15].initialValue = data.data[0].programName;
      }

      this.visibleDialogPro = false; //关闭弹窗
    },
    //取项目大类
    async initBigMarketType() {
      let res = [];
      let rd = await getBigMarketType();
      this.bigType = rd.data; //将大类集合存储在变量中
      for (let i in rd.data) {
        res.push({ text: rd.data[i].typeName, value: rd.data[i].typeId });
      }
      this.initForm[3].itemList = res;
    },
    //根据项目大类取项目小类
    async initMarketTypeSmall(parentTypeId) {
      let res = [];
      this.dataParams = { parentTypeId: parentTypeId };
      let rd = await getSmallMarketType(this.dataParams);
      for (let i in rd.data) {
        res.push({ text: rd.data[i].typeName, value: rd.data[i].typeId });
      }
      this.initForm[4].itemList = res;
    },
    //保存方法
    saveDialog() {
      this.saveLoading = true;
      let allData = Object.assign({}, this.formData);
      this.$refs.FormPanel.excuteFormData(this.$refs.FormPanel.form);

      let subForm = this.$refs.FormPanel.form;
      //判断开始日期是否小于结束日期
      let planStartDate = subForm.planStartDate;
      let planEndDate = subForm.planEndDate;
      if (planStartDate != null && planStartDate != '' && planEndDate != null && planEndDate != '') {
        if (formatdateByDay(planStartDate) > formatdateByDay(planEndDate)) {
          this.$notify.error({ title: '提示信息', message: '开始日期不可以大于结束日期!' });
          this.saveLoading = false;
          return;
        }
      }
      //转换项目月份日期格式
      let activityMonth = subForm.activityMonth;
      if (activityMonth != null && activityMonth != '' && activityMonth.indexOf('00:00:00') < 0) {
        subForm.activityMonth = activityMonth + '-01 00:00:00';
      }

      allData = Object.assign(allData, subForm);
      allData.modelList = this.modelIdList; //车型列表
      allData.projectProgramId = this.projectProgramId; //项目ID
      //状态设置为计划未提交
      allData.planStatus = types.DEALER_PROJECT_STATUS_PLAN_NOT_SUBMIT;
      let filesInfo = allData.uploadFileList;
      let fileUrlList = [];
      //获取附件，转为list类型
      for (let i = 0; i < filesInfo.length; i++) {
        fileUrlList.push(Object.assign({}, { name: filesInfo[i].name }, { url: filesInfo[i].url }));
      }
      allData.filesInfo = fileUrlList;
      //格式化项目月份
      // allData.activityMonth = allData.activityMonth+'-01 00:00:00';
      //处理计划开展/投放时间 多时间内容
      if (allData.planLaunchReleaseTimeList != null && allData.planLaunchReleaseTimeList.length > 0) {
        let planLaunchReleaseTime = '';
        for (let i in allData.planLaunchReleaseTimeList) {
          if (planLaunchReleaseTime == '') {
            planLaunchReleaseTime = formatdateByDay(allData.planLaunchReleaseTimeList[i]);
          } else {
            planLaunchReleaseTime += ',' + formatdateByDay(allData.planLaunchReleaseTimeList[i]);
          }
        }
        allData.planLaunchReleaseTime = planLaunchReleaseTime;
      }
      this.save(allData);
    },
    //作废方法
    async nullifyDialog() {
      this.$confirm('是否确定作废?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          let res = await nullifyPlanById(this.options.id);
          if (res.resultCode === 200) {
            this.$notify.success({ title: '提示信息', message: '作废成功!' });
            // 重新加载
            this.closeDialog('refresh');
          } else {
            this.$notify.error({ title: '提示信息', message: res.errMsg || '作废失败!' });
          }
        })
        .catch(() => {});
    },
    //提交方法
    submitDialog() {
      //获取表内容
      this.$refs.FormPanel.SUBMIT_FORM();
    },
    //表单提交后
    changeHandle(data) {
      this.saveLoading = true;
      //判断开始日期是否小于结束日期
      let planStartDate = data.planStartDate;
      let planEndDate = data.planEndDate;
      if (planStartDate != null && planStartDate != '' && planEndDate != null && planEndDate != '') {
        if (formatdateByDay(planStartDate) > formatdateByDay(planEndDate)) {
          this.$notify.error({ title: '提示信息', message: '开始日期不可以大于结束日期!' });
          return;
        }
      }
      this.formData = Object.assign(this.formData, data);

      let allData = Object.assign({}, this.formData);

      //转换项目月份日期格式
      let activityMonth = allData.activityMonth;
      if (activityMonth != null && activityMonth != '' && activityMonth.indexOf('00:00:00') < 0) {
        allData.activityMonth = activityMonth + '-01 00:00:00';
      }

      allData.modelList = this.modelIdList; //车型列表
      allData.projectProgramId = this.projectProgramId; //项目ID
      //状态设置为计划已提交
      allData.planStatus = types.DEALER_PROJECT_STATUS_PLAN_SUBMIT;
      let filesInfo = allData.uploadFileList;
      let fileUrlList = [];
      //获取附件，转为list类型
      for (let i = 0; i < filesInfo.length; i++) {
        fileUrlList.push(Object.assign({}, { name: filesInfo[i].name }, { url: filesInfo[i].url }));
      }
      allData.filesInfo = fileUrlList;
      //处理计划开展/投放时间 多时间内容
      if (allData.planLaunchReleaseTimeList != null && allData.planLaunchReleaseTimeList.length > 0) {
        let planLaunchReleaseTime = '';
        for (let i in allData.planLaunchReleaseTimeList) {
          if (planLaunchReleaseTime == '') {
            planLaunchReleaseTime = formatdateByDay(allData.planLaunchReleaseTimeList[i]);
          } else {
            planLaunchReleaseTime += ',' + formatdateByDay(allData.planLaunchReleaseTimeList[i]);
          }
        }
        allData.planLaunchReleaseTime = planLaunchReleaseTime;
      }
      this.save(allData);
    },
    //保存
    async save(data) {
      console.log('保存了！', data);
      let res;
      if (this.options.formType === 'add') {
        //添加
        res = await addData(data);
      } else {
        //修改
        res = await editData(this.options.id, data);
      }
      if (res.resultCode === 200) {
        this.$notify.success({ title: '提示信息', message: '保存成功!' });
        // 重新加载
        this.closeDialog('refresh');
      } else {
        this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
        this.closeDialog();
      }
    },
    //取消操作
    closeDialog(type) {
      this.$emit('close', { visible: false, type: type });
    },
    //搜索展开收起后
    collapseHandle() {
      this.$emit('onCollapse');
    },
    //创建搜索配置
    creatFilterList() {
      return [
        {
          //标签
          type: 'BREAK_SPACE',
          label: '项目基本信息',
          style: {},
        },
        { type: 'INPUT', label: '项目编号', fieldName: 'planCode', placeholder: '系统自动生成', initialValue: '', disabled: true },
        {
          type: 'SELECT',
          label: '项目状态',
          fieldName: 'planStatus',
          placeholder: '系统自动生成',
          initialValue: types.DEALER_PROJECT_STATUS_PLAN_NOT_SUBMIT,
          disabled: true,
          itemList: this.createDictList('2531'),
        },
        {
          type: 'INPUT',
          label: '方案编号',
          fieldName: 'programCode',
          placeholder: '请选择',
          initialValue: '',
          readonly: true,
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={() => this.openModelDialogPro()}></el-button>;
          },
        },
        {
          type: 'INPUT',
          label: '方案名称',
          fieldName: 'programName',
          disabled: true,
          placeholder: '系统自动生成',
          initialValue: '',
          selfCols: 1,
          rules: [{ max: 90, message: '长度最大90字符', trigger: 'change' }],
        },
        {
          type: 'SELECT',
          label: '项目大类',
          fieldName: 'projectMainClass',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
          change: (value) => {
            this.initMarketTypeSmall(value);
          },
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change',
            },
          ],
        },
        {
          type: 'DATE',
          label: '项目月份',
          fieldName: 'activityMonth',
          dateType: 'month',
          placeholder: '1-12月',
          initialValue: '',
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'blur',
            },
          ],
        },
        {
          type: 'SELECT',
          label: '项目小类',
          fieldName: 'projectSmallClass',
          placeholder: '请选择',
          initialValue: '',
          offsetRightCols: 1,
          itemList: [],
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change',
            },
          ],
        },
        {
          //标签
          type: 'BREAK_SPACE',
          label: '项目计划信息',
          style: {},
        },

        {
          type: 'INPUT',
          label: '项目名称',
          fieldName: 'projectName',
          placeholder: '请输入',
          initialValue: '',
          selfCols: 2,
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'blur',
            },
            { max: 90, message: '长度最大90字符', trigger: 'change' },
          ],
        },
        {
          type: 'TEXT_AREA',
          label: '项目描述',
          fieldName: 'projectDesc',
          placeholder: '详细描述项目开展情况及费用计划使用情况',
          initialValue: '',
          selfCols: 2,
          row: 4,
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'blur',
            },
          ],
        },
        {
          type: 'MULTIPLE_CHECKBOX',
          label: '车型',
          selfCols: 2,
          fieldName: 'model',
          initialValue: [],
          itemList: [], //复选框数据源

          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change',
            },
          ],
        },
        //无字段
        {
          type: 'INPUT',
          label: '场地',
          fieldName: 'planProjectSite',
          placeholder: '（室内/室外）+面积',
          initialValue: '',
          selfCols: 2,
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'blur',
            },
            { max: 300, message: '长度最大300字符', trigger: 'change' },
          ],
        },
        {
          type: 'SELECT',
          label: '合作方式',
          fieldName: 'cooperationMethod',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.createDictList('2532'),
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change',
            },
          ],
        },
        {
          type: 'DATES',
          label: '计划开展/投放时间',
          fieldName: 'planLaunchReleaseTimeList',
          placeholder: '请选择',
          valueFormat: 'yyyy-MM-dd',
          initialValue: null,
          selfCols: 2,
          change: (value) => {
            this.initReleaseTimeSmall(value);
          },
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'blur',
            },
          ],
        },
        {
          type: 'DATE',
          label: '开始日期',
          fieldName: 'planStartDate',
          placeholder: '',
          initialValue: '',
          disabled: true,
          valueFormat: 'yyyy-MM-dd',
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'blur',
            },
          ],
        },
        {
          type: 'DATE',
          label: '结束日期',
          fieldName: 'planEndDate',
          placeholder: '',
          initialValue: '',
          disabled: true,
          valueFormat: 'yyyy-MM-dd',
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'blur',
            },
          ],
        },
        {
          type: 'INPUT_NUMBER',
          label: '投放天数',
          fieldName: 'planTimeDay',
          placeholder: '',
          selfCols: 1,
          initialValue: null,
          disabled: true,
          rules: [{ required: true, message: '请输入', trigger: 'blur' }],
        },
        {
          type: 'INPUT',
          label: '项目地点',
          fieldName: 'planProjectLocation',
          placeholder: '',
          initialValue: '',
          selfCols: 1,
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'blur',
            },
            { max: 300, message: '长度最大300字符', trigger: 'change' },
          ],
        },
        //无字段
        {
          type: 'INPUT',
          label: '展位计划金额',
          fieldName: 'planBoothAmount',
          placeholder: '单位（元）',
          initialValue: undefined,
          numberFormat: true,
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'blur',
            },
            { pattern: /[\d\.]+/g, message: '请输入数字', trigger: 'blur' },
          ],
        },

        {
          type: 'INPUT_NUMBER',
          label: '目标集客数',
          fieldName: 'targetGuestsNum',
          placeholder: '数字',
          initialValue: undefined,
          disabled: true,
          precision: 0,
          min: 0,
          rules: [],
          rulesTmp: [{ required: true, message: '请输入', trigger: 'blur' }],
        },
        //无字段
        {
          type: 'INPUT',
          label: '搭建运营计划金额',
          fieldName: 'planBuildAmount',
          placeholder: '单位（元）',
          initialValue: undefined,
          numberFormat: true,
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'blur',
            },
            { pattern: /[\d\.]+/g, message: '请输入数字', trigger: 'blur' },
          ],
        },
        {
          type: 'INPUT_NUMBER',
          label: '目标订单数',
          fieldName: 'targetOrderNum',
          placeholder: '数字',
          initialValue: undefined,
          disabled: true,
          precision: 0,
          min: 0,
          rules: [],
          rulesTmp: [{ required: true, message: '请输入', trigger: 'blur' }],
        },
        // { type: 'SELECT', label: '预算类别', fieldName: 'budgetType', placeholder: '请选择', initialValue: '', itemList: this.createDictList('8052'),
        //     rules: [
        //         {
        //         required: true,
        //         message: '必填',
        //         trigger: 'change'
        //         }
        //     ]
        // },

        {
          type: 'INPUT',
          label: '计划项目金额',
          fieldName: 'planProjectAmount',
          placeholder: '单位（元）',
          initialValue: undefined,
          numberFormat: true,
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'blur',
            },
            { pattern: /[\d\.]+/g, message: '请输入数字', trigger: 'blur' },
          ],
        },
        {
          type: 'INPUT_NUMBER',
          label: '目标留档数',
          fieldName: 'targetRetentionNum',
          placeholder: '数字',
          initialValue: undefined,
          disabled: true,
          precision: 0,
          min: 0,
          rules: [],
          rulesTmp: [{ required: true, message: '请输入', trigger: 'blur' }],
        },

        { type: 'INPUT', label: '计划批准金额', fieldName: 'planApproveAmount', placeholder: '单位（元）', initialValue: undefined, disabled: true, numberFormat: true },
        {
          type: 'UPLOAD_FILE',
          label: '附件',
          fieldName: 'uploadFileList',
          initialValue: [],
          selfCols: 2,

          upload: {
            actionUrl: '/api/file/oss/upload', //上传的地址
            // tipText: '支持PDF/JPG/PNG/RAR格式，单个文件最大100M',
            limit: 0,
            max: 1024 * 100,
            fileTypes: ['jpg', 'png', 'pdf', 'rar', 'ppt', 'pptx'],
          },
        },
      ];
    },
    //创建表格列配置
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        // { title: '项目审核部门', dataIndex: 'reviewDept', sorter: true },
        { title: '项目审核部门', dataIndex: 'deptName', sorter: true },
        { title: '项目审核人', dataIndex: 'reviewPersionName', sorter: true },
        { title: '经销商简称', dataIndex: 'dealerShortname', sorter: true },
        {
          title: '审核状态',
          dataIndex: 'reviewStatus',
          sorter: true,
          render: (props) => {
            //编码转汉字
            return <span>{this.createDictText(props.row.reviewStatus, '2531')}</span>;
          },
        },
        {
          title: '审核时间',
          dataIndex: 'reviewDate',
          sorter: true,
          render: (props) => {
            return <span>{formatdateByTime(props.row.reviewDate)} </span>;
          },
        },
        { title: '审核意见', dataIndex: 'overruleReason', sorter: true },
      ];
    },
  },
};
</script>

<style scoped>
</style>